#include <termios.h>
#include <fcntl.h>

typedef signed char s8;
typedef unsigned char u8;

typedef signed short s16;
typedef unsigned short u16;

typedef signed int s32;
typedef unsigned int u32;

typedef signed long long s64;
typedef unsigned long long u64;


#define SERIAL_0				"/dev/ttyUSB1"

void SetSerial(int fd,int speed)
{
	struct termios opt;

	tcgetattr(fd, &opt);	
	opt.c_cc[VTIME] = 1;
	opt.c_cc[VMIN] = 10;
	//----
	opt.c_oflag &= ~(INLCR | IGNCR | ICRNL);
	opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	opt.c_oflag &= ~(ONLCR | OCRNL);	
	//sh add set   不加这个的话，0d 0a两字符 存在buff里都是0a了，
	opt.c_iflag &= ~(IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK|ISTRIP|INLCR|IGNCR|ICRNL|IUCLC|IXON|IXOFF|IXANY); 
	opt.c_oflag &= ~OPOST;
	opt.c_lflag &= ~(ECHO|ECHONL|ISIG|IEXTEN|ICANON);
	tcflush(fd, TCIFLUSH);

	cfsetispeed(&opt, speed);
	cfsetospeed(&opt, speed);
	//cfsetispeed(&opt, B57600);
	//cfsetospeed(&opt, B57600);
	tcsetattr(fd, TCSANOW, &opt);
}

int SerialOpen(u8 *file,int speed)
{
	int fd;
	fd=open(file, O_RDWR| O_NOCTTY | O_NDELAY);
	if(fd<0)
	{
		fd=-1;
	}
	else
	{
		SetSerial(fd,speed);		
	}
	return fd;

}
int SerialSend(int fd,u8 *p,u32 len)
{
	int ret;
	if(fd<0)
	{
		ret=-1;;
	}
	else
	{
		ret=write(fd,p,len);
	}
	return ret;
}
int SerialRead(int fd,u8 *p,u32 len)
{
	int ret;
	if(fd<0)
	{
		ret=-1;
	}
	else
	{
		ret=read(fd,p,len);
	}
	return ret;
}
int SerialClose(int fd)
{
	if(fd<0)
	{
		return -1;
	}
	else
	{		
		close(fd);	
	}
	return -1;
}

int main(void)
{
	int SerialDev_fd;
	u8 str[1024];
	int i,ret;	

	SerialDev_fd=SerialOpen(SERIAL_0,B115200);	
	if(SerialDev_fd==-1)
	{
		printf("Serial Open Err!\r\n");
		return 0;
	}
	while(1)
	{
		usleep(10);
		ret=SerialRead(SerialDev_fd,str,1024);
		if(ret>0)
		{				
			for(i=0;i<ret;i++)
			{
				printf("0x%x ",str[i]);
			}

		}	
		printf("\r\n");
	}
	
       printf("linux love \r\n");
	return 0;
}
